<?php
namespace Admin\Model;
use Common\Model\CommonModel;
class VarModel extends  CommonModel{
	
	//自动验证
	protected $_validate = array(
			//array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
			array('name', 'require', '名称不能为空！', 1, 'regex', 3),
			array('catid', 'require', '分类不能为空！', 1, 'regex', 3),
		
		
		
	);
	

	public function get_admin_tree($catid,$value){
		 
		import("Tree");
		$tree = new \Tree();
	
		$result = $this->where(array("catid"=>$catid))->order(array("listorder" => "DESC"))->select();
		 
		 
		foreach ($result as $r) {
			 
			$r['selected'] = $r['id'] == $value ? 'selected' : '';
			
			 
			$array[] = $r;
		}
		 
		$str = "<option value='\$id' \$selected \$disable>\$spacer \$name</option>";
		$tree->init($array);
		$select_categorys = $tree->get_tree(0, $str);
		 
		return $select_categorys;
		 
		 
		 
	}
	
	
	/**
	 * 后台有更新/编辑则删除缓存
	 * @param type $data
	 */
	public function _before_write() {
		parent::_before_write();
		$this->data_cache();
	}
	
	public function _after_insert() {
		parent::_after_insert();
		$this->data_cache();
	}

	public function data_cache(){
			
		
		$cate=D("VarCat")->select();
		
		foreach ($cate as $k=>$v){
			
			$data=$this->field('id,name,default,thumb,parentid,kuo_1')->where(array("status"=>1,"catid"=>$v[id]))->order(array("listorder" => "DESC","id"=>"ASC"))->select();
			$s=array();
			foreach ($data as $key=>$t){
				
				$s[$t[id]]=$t;
				
				$all[$t[id]]=$t[name];
			}
			
			F("Var_".$v[tag],$s);
			
			
			
			
			$map[status]='1';
			$map[catid]=$v[id];
			$map[parentid]=array("NEQ",'0');
			
			$count=$this->where($map)->count();
			
			if($count){
			import("Tree");
			$tree = new \Tree();
			$tree->init($data);
			 
			
			$result = $tree->get_tree_array(0);
			
			F("Var_".$v[tag]."_tree",$result);
			}
			
		};
		
		
		F("Var",$all);
	
			
		
			
			
	}
	
	
}